#!/bin/sh
set -eu

. /etc/default/earlyoom

do_start() {
	if ps -p "$(cat /var/run/earlyoom.pid)" > /dev/null
	then
		echo "earlyoom is already running."
	else
		echo "Starting earlyoom..."
		nohup /usr/bin/earlyoom $EARLYOOM_ARGS > /var/log/earlyoom.log 2>&1 &
		echo "$!" > /var/run/earlyoom.pid
	fi
}

do_stop() {
	if ps -p "$(cat /var/run/earlyoom.pid)" > /dev/null
	then
		echo "Stopping earlyoom..."
		kill -15 "$(cat /var/run/earlyoom.pid)"
	else
		echo "earlyoom is not running."
	fi
}

do_force_stop() {
	if ps -p "$(cat /var/run/earlyoom.pid)" > /dev/null
	then
		echo "Killing earlyoom..."
		kill -9 "$(cat /var/run/earlyoom.pid)"
	else
		echo "earlyoom appears to not be running."
	fi
}

do_restart() {
	do_stop
	do_start
}

do_status() {
	if ps -p "$(cat /var/run/earlyoom.pid)" > /dev/null
	then
		echo "earlyoom is running with pid $(cat /var/run/earlyoom.pid)."
	else
		echo "earlyoom is not running."
	fi
}

case $1 in
	start)
		do_start
		;;
	stop)
		do_stop
		;;
	restart)
		do_restart
		;;
	force-stop)
		do_force_stop
		;;
	status)
		do_status
		;;
	*)
		echo "USAGE: rc.earlyoom (start|stop|force-stop|restart|status)"
		;;
esac
